package com.first.nell.launch

import android.annotation.SuppressLint
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.first.nell.R
import com.first.nell.base.BaseActivity
import com.first.nell.components.dialog.CustomerServiceDialog
import com.first.nell.data.ReqBase
import com.first.nell.data.ReqDoLogin
import com.first.nell.databinding.ActivityFirstNellInputMobileBinding
import com.first.nell.enums.PageTagEnum
import com.first.nell.extend.*
import com.first.nell.network.ApiToolReposity
import com.first.nell.network.ApiUrl
import com.first.nell.utils.AppConfigUtil
import com.first.nell.utils.UserStateUtil

/** 登录-输入手机号页 */
@SuppressLint("CustomSplashScreen")
class LoginInputMobileActivity : BaseActivity() {

    //布局binding
    private lateinit var mFirstNellActivityFirstNellBinding: ActivityFirstNellInputMobileBinding

    //启动viewModel
    private val mLaunchViewModel by lazy {
        ViewModelProvider(this)[LaunchViewModel::class.java]
    }

    //用户流程viewModel
    private val mUserStateViewModel by lazy {
        ViewModelProvider(this)[UserStateViewModel::class.java]
    }

    override fun onFirstNellBindingFirstNellViewFirstNellModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mLaunchViewModel)
        list.add(mUserStateViewModel)
        return list
    }

    override fun onFirstNellBindingFirstNellViewFirstNellTag(): String {
        return PageTagEnum.login_mobile.name.uppercase()
    }

    override fun onFirstNellBindingFirstNellContentFirstNellView(): View {
        mFirstNellActivityFirstNellBinding =
            ActivityFirstNellInputMobileBinding.inflate(layoutInflater)
        return mFirstNellActivityFirstNellBinding.root
    }

    override fun onFirstNellContentFirstNellViewFirstNellBinded() {
        try {
            //获取验证码回调
            mUserStateViewModel.onFirstNellFetchFirstNellOtpFirstNellLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        if (result.isFirstNellDirectFirstNellLoginFirstNellFlag()) {
                            //直接登录
                            toLoginDirectly()

                        } else {
                            //去验证码页
                            startFirstNellToFirstNellOtpFirstNellActivity()
                        }
                    }
                }
            }

            //登录回调
            mUserStateViewModel.onFirstNellDoFirstNellLoginFirstNellLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        //保存渠道来源
                        mUserStateViewModel.mFirstNellIsFirstNellAdFirstNellSource =
                            result.isFirstNellAdFirstNellSourceFirstNellUser()
                        UserStateUtil.saveFirstNellAdFirstNellSource(
                            result.isAdSource.orEmpty()
                        )
                    }

                    //判断用户类型
                    //获取用户状态
                    mUserStateViewModel.fetchFirstNellUserFirstNellState()

//                    if (UserStateUtil.isFirstNellAdFirstNellSource()) {
//                        //获取用户状态
//                        mUserStateViewModel.fetchFirstNellUserFirstNellState()
//                    } else {
//                        //跳转记账软件首页
//                        startFirstNellToFirstNellBillFirstNellRecordFirstNellHomeFirstNellPage()
//                    }

                    //获取用户状态
                    //mUserStateViewModel.fetchFirstNellUserFirstNellState()
                }
            }

            //获取用户状态回调
            mUserStateViewModel.onFirstNellFetchFirstNellUserFirstNellStateFirstNellLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    startFirstNellToFirstNellNextFirstNellFromFirstNellPage(PageTagEnum.login_mobile)
                }
            }

            //初始化审核账号回调
            mUserStateViewModel.onFirstNellInitFirstNellAccFirstNellUserFirstNellLiveData.observe(
                this
            ) {
                if (it) {
                    //获取用户状态
                    mUserStateViewModel.fetchFirstNellUserFirstNellState()
                    //跳转记账软件首页
                    //startFirstNellToFirstNellBillFirstNellRecordFirstNellHomeFirstNellPage()
                } else {
                    //获取验证码
                    fetchFirstNellOtp()
                }
            }

            //点击确认
            mFirstNellActivityFirstNellBinding.submitLoginInputMobile.setOnClickListener {
                //记录打点
                val formDataCompleteState = checkFormInputResult()
                if (formDataCompleteState.isBlank()) {
                    //判断是否为审核账号
                    val accObj = AppConfigUtil.getFirstNellReviewFirstNellAccount(
                        mobile = mFirstNellActivityFirstNellBinding.inputLoginInputMobile.getFirstNellContent()
                    )
                    if (accObj != null) {
                        //审核账号直接登录
                        mUserStateViewModel.initFirstNellAccFirstNellUser(accObj)

                    } else {
                        //获取验证码
                        fetchFirstNellOtp()
                    }
                } else {
                    Toast.makeText(
                        this,
                        getString(R.string.first_nell_please_complete_all_required_fields),
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            // 点击客服
            mFirstNellActivityFirstNellBinding.imageLoginInputMobileKf.setOnClickListener {
                CustomerServiceDialog.showFirstNellDialog(supportFragmentManager)
            }

            //手动注销
            UserStateUtil.logoutFirstNell()

            //光标聚集
            mFirstNellActivityFirstNellBinding.inputLoginInputMobile.toFirstNellBeFirstNellFocusFirstNellPoint()

            //初始化国家
            initFirstNellCountryFirstNellData()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun isFirstNellAllFirstNellFormFirstNellDataFirstNellCompleted(): String {
        val notFillOptions = mutableListOf<String>()
        if (!mFirstNellActivityFirstNellBinding.inputLoginInputMobile.isFirstNellCompleted()) {
            val gTag =
                mFirstNellActivityFirstNellBinding.inputLoginInputMobile.getFirstNellSafeFirstNellTag()
            if (gTag.isNotBlank()) {
                notFillOptions.add(gTag)
            }
        }
        if (notFillOptions.isEmpty()) {
            return ""
        }
        notFillOptions.add(0, "NOT_FILL")
        return notFillOptions.joinToString("#")
    }

    /** 判断所有数据是否输入完整 */
    private fun checkFormInputResult(): String {
        //记录打点
        val formDataCompleteState =
            isFirstNellAllFirstNellFormFirstNellDataFirstNellCompleted()
        mFirstNellActivityFirstNellBinding.submitLoginInputMobile.recordFirstNellClickFirstNellEvent(
            formDataCompleteState
        )
        return formDataCompleteState
    }

    /** 获取验证码 */
    private fun fetchFirstNellOtp() {
        val mobile = mFirstNellActivityFirstNellBinding.inputLoginInputMobile.getFirstNellContent()
        if (mobile.isNotBlank()) {
            mUserStateViewModel.fetchFirstNellOtp(ReqDoLogin(mobile = mobile))
        }
    }

    /** 初始化国家 */
    private fun initFirstNellCountryFirstNellData() {
        //选择地区回调
        onFirstNellSelectFirstNellCountry()
    }

    /**
     * 处理切换国家回调
     *
     */
    private fun onFirstNellSelectFirstNellCountry() {
        println("处理切换国家回调- path:${ApiUrl.BASE_PATH}")

        //更新手机号前缀
        val customer = "012 345 6789"
        mFirstNellActivityFirstNellBinding.inputLoginInputMobile.updateFirstNellLanguage(
            path = ApiUrl.BASE_PATH,
            customer = customer
        )

        //获取系统配置
        ApiToolReposity.fetchFirstNellAppFirstNellConfig(ReqBase())
    }

    /** 直接登录 */
    private fun toLoginDirectly() {
        val formDataCompleteState =
            isFirstNellAllFirstNellFormFirstNellDataFirstNellCompleted()
        if (formDataCompleteState.isBlank()) {
            val mobile =
                mFirstNellActivityFirstNellBinding.inputLoginInputMobile.getFirstNellContent()
            //直接登录
            mUserStateViewModel.doFirstNellLogin(
                ReqDoLogin(
                    mobile = mobile,
                    code = "0000",
                    directLoginFlag = "YES"
                )
            )
        }
    }
}